package com.konsung.ksdc.manager.community;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.bean.MqttMsgNotice;
import com.konsung.ksdc.bean.netbean.ContactRequestNetBean;
import com.konsung.ksdc.bean.netbean.EmpNetBean;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.mqtt.MqttMsgUtils;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.BroadCastActions;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DateUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.widget.ConfirmPopupWindow;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.machine.NetPicActivity;
import com.konsung.ksdc.service.MqttService;
import com.squareup.picasso.Picasso;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 创建者     kgh
 * 创建时间   2016/6/14 18:29
 * 描述   用户详细资料
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */
public class ContactIndexActivity extends Activity {
    public static final int WHAT_HIDE_DIALOG = 1;
    private static final int WHAT_DELETE_CONTACT = 2;
    public static final String TYPE = "type";
    public static final String TYPE_ONE = "1";
    private RegisterUserNetBean user;

    @Bind(R.id.img_contact_pic)
    ImageView ivContactPic;

    @Bind(R.id.txt_contact_nick_name)
    TextView txtContactNickName;

    @Bind(R.id.txt_contact_user_name)
    TextView txtContactUserName;

    @Bind(R.id.txt_contact_name)
    TextView txtContactName;

    @Bind(R.id.txt_contact_telephone)
    TextView txtContactTelephone;

    @Bind(R.id.txt_contact_addr)
    TextView txtContactAddr;

    @Bind(R.id.txt_contact_note)
    TextView txtContactNote;

    @Bind(R.id.btn_add_contact)
    Button btnAddContact;

    @Bind(R.id.img_back)
    ImageView back;

    @Bind(R.id.btn_send)
    Button btnSend;

    @Bind(R.id.btn_delete)
    Button btnDelete;

    @Bind(R.id.ll_clear_msg)
    LinearLayout llClearMsg;

    private String data;

    private ProgressDialog progressDialog;

    private Handler handler;
    private ConfirmPopupWindow popupWindow;
    private ConfirmPopupWindow clearMsgWindow;
    private String picUrl;
    private String type = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_index);
        ButterKnife.bind(this);

        initHandler();

        Intent intent = getIntent();
        data = intent.getStringExtra("data");
        type = intent.getStringExtra(TYPE);
        user = new Gson().fromJson(data, RegisterUserNetBean.class);
        //查询本地数据库是否有该联系人
        RegisterUserNetBean u = this.findUserByUserId(user.getUserId());

        if (u == null) {
            btnSend.setVisibility(View.GONE);
            btnDelete.setVisibility(View.GONE);
            btnAddContact.setVisibility(View.VISIBLE);
        } else {
            btnAddContact.setVisibility(View.GONE);
            btnSend.setVisibility(View.VISIBLE);
            btnDelete.setVisibility(View.VISIBLE);
            if (Constants.TOPIC_KSBK.equals(user.getUserName())
                    || Constants.TOPIC_KSKF.equals(user.getUserName())) {
                btnDelete.setVisibility(View.GONE);
            }
        }

        initUserInfo();
        initEvent();

        RequestUtils.findEmployeeByUserId(user.getUserId(), new RequestCallback() {

            @Override
            public void onError(Call call, Exception e) {
                e.printStackTrace();
                Toast.makeText(ContactIndexActivity.this, "用户资料加载失败",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                EmpNetBean bean = responseBean.getEntity(EmpNetBean.class);
                initEmpInfo(bean);
            }
        });
    }

    /**
     * 初始化按钮事件
     */
    private void initEvent() {
        // 添加联系人
        btnAddContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!RequestUtils.isNetworkConnected(ContactIndexActivity.this)
                        || !MqttService.isMqttConnected()) {
                    Toast.makeText(ContactIndexActivity.this, getString(R.string.chat_unconnect),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                showConfirmAlert();
            }
        });

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openChart(user);
            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!RequestUtils.isNetworkConnected(ContactIndexActivity.this)
                        || !MqttService.isMqttConnected()) {
                    Toast.makeText(ContactIndexActivity.this, getString(R.string.chat_unconnect),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                showDeleteConfirm();
            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        llClearMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearMsg();
            }
        });
        ivContactPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ContactIndexActivity.this, NetPicActivity.class);
                intent.putExtra(NetPicActivity.PIC_URL, picUrl);
                startActivity(intent);
            }
        });
    }

    /**
     * 加载USER基本信息
     */
    private void initUserInfo() {
        // 头像
        picUrl = StringUtils.appendPicPath(user.getUserPic());
        Picasso.with(this)
                .load(picUrl)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(ivContactPic);

        // 昵称
        txtContactNickName.setText(user.getNickName());
        // 用户名
        txtContactUserName.setText("用户名：" + user.getUserName());
        // 名字
        txtContactName.setText(user.getEmpName());
        // 签名
        txtContactNote.setText(user.getUserNote());
    }

    /**
     * 初始化handler
     */
    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case WHAT_HIDE_DIALOG:
                        progressDialog.dismiss();
                        break;

                    case WHAT_DELETE_CONTACT:
                        sendDeleteMessage();
                        break;

                    default:
                        break;
                }
            }
        };
    }

    /**
     * 加载界面数据
     * @param bean bean类
     */
    private void initEmpInfo(EmpNetBean bean) {
        // 联系电话
        txtContactTelephone.setText(bean.getTelphone());
        // 家庭住址
        txtContactAddr.setText(bean.getAddr());
    }

    /**
     * 清除聊天记录
     */
    private void clearMsg() {
        clearMsgWindow = new ConfirmPopupWindow(ContactIndexActivity.this,
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            removeNotice();
                            removeMsg();
                            Toast.makeText(ContactIndexActivity.this,
                                    getString(R.string.clear_msg_success),
                                    Toast.LENGTH_SHORT).show();
                            clearMsgWindow.dismiss();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(ContactIndexActivity.this,
                                    getString(R.string.clear_msg_faild),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        clearMsgWindow.dismiss();
                    }
                });
        clearMsgWindow.setTitle(getString(R.string.confirm_clear_msg_title));
        clearMsgWindow.setTips(getString(R.string.confirm_clear_msg_tips));
        clearMsgWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 弹出删除确认弹窗
     */
    private void showDeleteConfirm() {
        popupWindow = new ConfirmPopupWindow(ContactIndexActivity.this,
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteContact();
                    }
                },
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });
        popupWindow.setTitle(getString(R.string.delete_confirm_title));
        popupWindow.setTips(getString(R.string.delete_confirm_tips));
        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 删除好友
     */
    private void deleteContact() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(getString(R.string.tip_deleting));
        progressDialog.setCancelable(false);
        progressDialog.show();

        String userId = NetConfig.currentUser.getUserId();
        RequestUtils.deleteContact(userId, user.getUserId(), new RequestCallback() {

            @Override
            public void onError(Call call, Exception e) {
                handler.sendEmptyMessage(WHAT_HIDE_DIALOG);

                e.printStackTrace();
                Toast.makeText(ContactIndexActivity.this,
                        getString(R.string.contact_delete_failed),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                String resultCode = responseBean.getResultCode();
                if (Constants.REQUEST_OK.equals(resultCode)) {

                    try {
                        handler.sendEmptyMessage(WHAT_DELETE_CONTACT);

                        removeLocal();
                        Toast.makeText(ContactIndexActivity.this, getString(R.string
                                .contact_delete_success), Toast.LENGTH_SHORT).show();

                        finish();
                    } catch (SQLException e) {
                        e.printStackTrace();
                        Toast.makeText(ContactIndexActivity.this, getString(R.string
                                .contact_delete_failed), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(ContactIndexActivity.this, getString(R.string
                            .contact_delete_failed), Toast.LENGTH_SHORT).show();
                }

                handler.sendEmptyMessage(WHAT_HIDE_DIALOG);
            }
        });
    }

    /**
     * 清除本地数据
     * @throws SQLException 数据库异常
     */
    private void removeLocal() throws SQLException {
        removeContact();
        removeNotice();
        removeMsg();

        Intent intent = new Intent();
        intent.setAction(BroadCastActions.ACTION_DELETE_CONTACT);
        sendBroadcast(intent);
    }

    /**
     * 删除聊天记录
     * @throws SQLException 数据库异常
     */
    private void removeMsg() throws SQLException {
        RuntimeExceptionDao dao = DatabaseHelper.getHelper(this)
                .getRuntimeExceptionDao(MqttMsgBean.class);
        DeleteBuilder db = dao.deleteBuilder();
        Where where = db.where();
        Where exp1 = where.eq("topicName", user.getUserName());
        Where exp2 = where.eq("topicName", NetConfig.currentUser
                .getUserName()).and().eq("contact", user.getUserId());
        Where expOr = where.or(exp1, exp2);
        where.and(where.eq("ownerUserId",
                NetConfig.currentUser.getUserId()), expOr);

        dao.delete(db.prepare());
    }

    /**
     * 删除提醒
     * @throws SQLException 数据库异常
     */
    private void removeNotice() throws SQLException {
        RuntimeExceptionDao dao = DatabaseHelper.getHelper(this)
                .getRuntimeExceptionDao(MqttMsgNotice.class);
        DeleteBuilder db = dao.deleteBuilder();
        db.where().eq("ownerUserId", NetConfig.currentUser.getUserId())
                .and()
                .eq("topicName", user.getUserId());
        dao.delete(db.prepare());
    }

    /**
     * 删除联系人
     * @throws SQLException 数据库异常
     */
    private void removeContact() throws SQLException {
        RuntimeExceptionDao dao = DatabaseHelper.getHelper(this)
                .getRuntimeExceptionDao(RegisterUserNetBean.class);
        DeleteBuilder db = dao.deleteBuilder();
        db.where().eq("userId", user.getUserId()).and().eq("ownerId", NetConfig.currentUser
                .getUserId());
        dao.delete(db.prepare());
    }

    /**
     * 弹出确认信息对话框
     */
    private void showConfirmAlert() {
        if (user.getUserId().equals(NetConfig.currentUser.getUserId())) {
            Toast.makeText(MyApplication.mCurrentActivity,
                    "不能添加当前账号为好友", Toast.LENGTH_SHORT).show();
            return;
        }

        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.alert_contact_request, null);
        final EditText etRequestMark = (EditText) view.findViewById(R.id.et_request_mark);
        etRequestMark.setText("你好，我是" + NetConfig.currentUser.getNickName());

        final AlertDialog.Builder customDia = new AlertDialog.Builder(this);
        customDia.setTitle("验证信息");
        customDia.setView(view);
        customDia.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                sendContactRequest(etRequestMark.getText().toString());
            }
        });
        customDia.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        customDia.create().show();
    }

    /**
     * 添加
     * @param mark 标记
     */
    private void sendContactRequest(String mark) {
        ContactRequestNetBean bean = new ContactRequestNetBean();
        bean.setRequestUserId(NetConfig.currentUser.getUserId());
        bean.setTargetUserId(user.getUserId());
        bean.setMark(mark);

        RequestUtils.addContactRequest(bean, new RequestCallback() {

            @Override
            public void onError(Call call, Exception e) {
                e.printStackTrace();
                Toast.makeText(MyApplication.mCurrentActivity,
                        "添加联系人失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                String resultCode = responseBean.getResultCode();
                String msg = responseBean.getEntity(String.class);

                if (Constants.REQUEST_OK.equals(resultCode)) {
                    btnAddContact.setVisibility(View.GONE);
                    sendRequestMessage();
                }

                Toast.makeText(ContactIndexActivity.this, msg,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 发送申请好友到对方
     */
    private void sendRequestMessage() {
        Gson gson = new Gson();

        String msgSendDate = DateUtils.getStringDateFormat(new Date(),
                DateUtils.yyyyMMddHHmmss);
        String targetType = MqttMsgUtils.MSG_TARGET_TYPE_PERSONAL;

        MqttMsgBean bean = new MqttMsgBean();
        bean.setMsgContent(gson.toJson(NetConfig.currentUser));
        bean.setMsgSendDate(msgSendDate);
        bean.setMsgTargetType(targetType);
        bean.setMsgType(MqttMsgUtils.MSG_TYPE_REQUEST_RECEIVED);
        bean.setContact(NetConfig.currentUser.getUserId());
        bean.setTopicName(user.getUserName());

        try {
            byte[] msgContent = MqttMsgUtils.msgBeanParseByte(bean);
            MqttService.mqttClient.publish(bean.getTopicName(), msgContent, 2, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送删除好友消息到对方
     */
    private void sendDeleteMessage() {
        Gson gson = new Gson();

        String msgSendDate = DateUtils.getStringDateFormat(new Date(),
                DateUtils.yyyyMMddHHmmss);
        String targetType = MqttMsgUtils.MSG_TARGET_TYPE_PERSONAL;

        MqttMsgBean bean = new MqttMsgBean();
        bean.setMsgContent(NetConfig.currentUser.getUserName());
        bean.setMsgSendDate(msgSendDate);
        bean.setMsgTargetType(targetType);
        bean.setMsgType(MqttMsgUtils.MSG_TYPE_DELETE_CONTACT);
        bean.setContact(NetConfig.currentUser.getUserId());
        bean.setTopicName(user.getUserName());

        try {
            byte[] msgContent = MqttMsgUtils.msgBeanParseByte(bean);
            MqttService.mqttClient.publish(bean.getTopicName(), msgContent, 2, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从本地数据库取好友数据
     * @param userId 用户id
     * @return 注册数据
     */
    private RegisterUserNetBean findUserByUserId(String userId) {
        RuntimeExceptionDao dao = DatabaseHelper.getHelper(this)
                .getRuntimeExceptionDao(RegisterUserNetBean.class);
        QueryBuilder queryBuilder = dao.queryBuilder();
        //根据对方的userid来查询自己好友里有没有该用户
        try {
            queryBuilder.where().eq("userId", userId).and().eq("ownerId", NetConfig.currentUser
                    .getUserId());
            List<RegisterUserNetBean> users = dao.query(queryBuilder.prepare());
            if (users != null && !users.isEmpty()) {
                return users.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 打开聊天界面
     * @param user 用户
     */
    public void openChart(RegisterUserNetBean user) {
        if (null != type && type.equals(TYPE_ONE)) {
            finish();
        } else {
            String contactUserId = user.getUserId();
            String contactUserName = user.getUserName();
            String nickName = user.getNickName();
            String picPath = user.getUserPic();
            Intent intent = new Intent(this, ChatActivity.class);
            intent.putExtra("userId", contactUserId);
            intent.putExtra("topicName", contactUserName);
            intent.putExtra("nickName", nickName);
            intent.putExtra("picPath", picPath);
            Gson gson = new Gson();
            intent.putExtra("data", gson.toJson(user));
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }
}
